/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SearchPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.presenter;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.base.AppUI;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.QuoteApi;
import io.bhex.sdk.quote.bean.NewCoinPairListBean;
import io.bhex.sdk.quote.bean.TickerBean;
import io.bhex.sdk.socket.NetWorkObserver;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.app.market.bean.FavoriteRecordBean;
import io.bhex.sdk.quote.bean.QuoteBean;
import io.bhex.app.market.bean.SearchRecordBean;
import io.bhex.sdk.quote.bean.TickerListBean;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.app.utils.KlineUtils;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;

/**
 * ================================================
 * 描   述：搜索
 * ================================================
 */

public class SearchPresenter extends BasePresenter<SearchPresenter.SearchUI> {
    List<CoinPairBean> coinPairList;

    /**
     * @param searchTxt
     */
    public void search(String searchTxt) {
        if (TextUtils.isEmpty(searchTxt)) {
            showHistory();
        } else {
            filterSearchList(searchTxt.trim());
        }
    }

    /**
     * 过滤搜索结果
     * @param searchTxt
     */
    private void filterSearchList(String searchTxt) {
        if (coinPairList == null || coinPairList.isEmpty()) {
            getCoinPairList(searchTxt,true);
        }else{
            startFilter(coinPairList,searchTxt);
        }
    }

    //过滤集合
    private List<CoinPairBean> filterList = new ArrayList<>();
    /**
     * 开始过滤
     * @param coinPairList
     * @param searchTxt
     */
    private void startFilter(List<CoinPairBean> coinPairList, String searchTxt) {
        if (coinPairList == null || coinPairList.isEmpty()) {
            return;
        }
        filterList.clear();
        for (CoinPairBean coinPairBean : coinPairList) {
            if (isMatch(searchTxt,coinPairBean)) {
                filterList.add(coinPairBean);
            }
        }

        getUI().showMarket(filterList,false);
    }

    private boolean isMatch(String searchContent, CoinPairBean coinPairBean) {
        String quoteTokenName = coinPairBean.getQuoteTokenName();
        String baseTokenName = coinPairBean.getBaseTokenName();
        if (!TextUtils.isEmpty(searchContent)) {
            searchContent = searchContent.toUpperCase();
        }
        if (!TextUtils.isEmpty(baseTokenName)) {
            baseTokenName = baseTokenName.toUpperCase();
            if (baseTokenName.contains(searchContent)) {
                return true;
            }
        }
        if (!TextUtils.isEmpty(quoteTokenName)) {
            quoteTokenName = quoteTokenName.toUpperCase();
            return quoteTokenName.contains(searchContent);
        }

        return false;
    }

    public interface SearchUI extends AppUI {
        void showMarket(List<CoinPairBean> coinPairList, boolean isShowHistory);

        void showHistory(List<CoinPairBean> data);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, SearchUI ui) {
        super.onUIReady(activity, ui);
        getCoinPairList("",false);

        //显示历史搜索记录
        showHistory();
    }



    /**
     * 获取币对列表
     * @param searchTxt
     */
    public void getCoinPairList(final String searchTxt, final boolean isSearch) {
        SymbolDataManager.GetInstance().getNewCoinPairList(new SimpleResponseListener<NewCoinPairListBean>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(NewCoinPairListBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    coinPairList = response.symbol;
//                    getRealTimeData();
                    if (isSearch) {
                        startFilter(response.symbol,searchTxt);
                    }else{
                        getUI().showMarket(coinPairList,false);
                    }
                }
            }
        });
    }

    public void showHistory() {
        SearchRecordBean searchRecord = KlineUtils.getSearchRecord();
        if (searchRecord != null) {
            List<CoinPairBean> searchRecordList = searchRecord.getData();
            if (searchRecordList != null) {
                FavoriteRecordBean favorite = KlineUtils.getFavorite();
                if (favorite != null) {
                    List<CoinPairBean> favoriteList = favorite.getData();
                    if (favoriteList != null) {
                        for (CoinPairBean searchItem : searchRecordList) {
                            boolean isFavorite = SymbolDataManager.GetInstance().isFavorite(searchItem);
                            searchItem.setFavorite(isFavorite);
                        }
                    }
                }

                getUI().showHistory(searchRecordList);
                return;
            }
        }
        getUI().showHistory(null);
    }


    /**
     * 拼接行情参数
     *
     * @return
     */
    private String getSymbolsListStr() {
        StringBuffer stringBuffer = new StringBuffer();
        if (coinPairList != null) {
            for (CoinPairBean coinPairBean : coinPairList) {
                if (coinPairBean != null) {
                    String symbol = coinPairBean.getExchangeId() + "." + coinPairBean.getSymbolId();
                    if (stringBuffer.toString().length() > 0) {
                        stringBuffer.append("," + symbol);
                    } else {
                        stringBuffer.append(symbol);
                    }
                }
            }
        }
        return stringBuffer.toString();
    }

    public void getRealTimeData(){
        String symbolsListStr = getSymbolsListStr();
        QuoteApi.SubTickers(symbolsListStr, new NetWorkObserver<TickerListBean>() {
            @Override
            public void onShowUI(TickerListBean response) {
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;

                List<TickerBean> datas = response.getData();
                if (datas != null) {
                    for (TickerBean data : datas) {
                        handleSocketMarketList(data);
                    }
                }
            }

            @Override
            public void onError(String error) {
            }
        });

    }

    private void handleSocketMarketList(TickerBean tickerBean) {
        String symbolTicker = tickerBean.getS();
        if (coinPairList != null) {
            for (CoinPairBean coinPairBean : coinPairList) {
                String symbolId = coinPairBean.getSymbolId();
                if (symbolId.equals(symbolTicker)) {
                    coinPairBean.setTicker(tickerBean);
                }
            }

        }
        if(filterList != null && filterList.size() > 0)
            getUI().showMarket(filterList,false);
    }

}
